<template>
	<div class="div1">
		<el-breadcrumb separator="/">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>咨询师管理</el-breadcrumb-item>
			<el-breadcrumb-item>收费标准管理</el-breadcrumb-item>
		</el-breadcrumb>
	</div>
	<div>
		<div class="div2">
			<span class="spanTop">咨询师姓名</span>
			<el-input size="large" v-model="searchName" style="width: 240px" placeholder="请输入咨询师姓名" clearable
				@clear="query" />
			<el-button @click="query" type="primary" size="large" class="bt1">搜索</el-button>
			<el-button type="primary" @click="createOrUpdate('')" size="large" class="bt1">新增收费标准</el-button>
			<el-button type="danger" size="large" class="bt1" @click="removeAll">批量删除</el-button>
		</div>

		<el-table :data="tableData" style="width: 100%;margin-top: 10px;" border
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" />
			<el-table-column fixed prop="id" label="ID" />
			<el-table-column prop="chargeCategory.categoryName" label="收费分类类别" />
			<el-table-column prop="price" label="收费价格" />
			<el-table-column prop="consultationCount" label="咨询数量" />
			<el-table-column prop="consultant.name" label="咨询师姓名" />
			<el-table-column fixed="right" label="操作" width="200">
				<template #default="scope">
					<el-button type="primary" @click="createOrUpdate(scope.row)">编辑</el-button>
					<el-button type="danger" @click="remove(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<el-dialog v-model="dialogFormVisible" :title="form.id ? '编辑收费标准' : '新增收费标准'" width="800" @close="handleClose">
			<el-form>
				<el-form-item label="收费分类" :label-width="formLabelWidth">
					<el-select v-model="form.categoryId" placeholder="请选择收费分类" size="large">
						<el-option v-for="item in AllCounselorLevel" :value="item.id" :label="item.categoryName"
							:key="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="收费价格" :label-width="formLabelWidth">
					<el-input size="large" v-model="form.price" autocomplete="off" />
				</el-form-item>
				<el-form-item label="咨询师" :label-width="formLabelWidth">
					<el-select v-model="form.consultantId" placeholder="请选择咨询师" size="large">
						<el-option v-for="item in AllCounselorName" :value="item.id" :label="item.name"
							:key="item.id" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button @click="dialogFormVisible = false;add()">确定</el-button>
				</div>
			</template>
		</el-dialog>
		<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10,15, 20]"
			:size="size" layout="total, sizes, prev, pager, next, jumper" :total=" total"
			@size-change="handleSizeChange" @current-change="handleCurrentChange" v-if="total !=0" />
	</div>
</template>
<script setup>
	import {
		onMounted,
		ref,
		reactive,
		computed,
		watch
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	import {
		getCurrentInstance
	} from 'vue';

	const axios = getCurrentInstance().appContext.config.globalProperties.axios
	const tableData = ref([])
	const currentPage = ref(1) // 当前页
	const pageSize = ref(10) // 每页显示条目数
	const size = 'default' // 分页大小
	const total = ref(0)
	const searchName = ref('')
	const searchCounselorLevelName = ref('')
	const searchAddress = ref('')
	const searchPhone = ref('')

	const form = ref({
		categoryId: '',
		categoryName: '',
		consultationCount: '',
		consultantId: '',
		price: '',
		name: '',
		id: '',
	})

	const dialogFormVisible = ref(false)
	const formLabelWidth = '100px'
	const AllCounselorLevel = ref([])
	const AllCounselorName = ref([])

	const getAllCounselorLevel = () => {
		axios.get('chargeCategory', ).then((resp) => {
			console.log(resp.data);
			AllCounselorLevel.value = resp.data
		});
	}
	const getAllCounselorName = () => {
		axios.get('consultant', ).then((resp) => {
			console.log("咨询师：", resp.data);
			AllCounselorName.value = resp.data
		});
	}

	function query() {
		axios.get(
			`charge/page?counselorName=${searchName.value}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`,
		).then(resp => {
			tableData.value = resp.data.list;
			total.value = resp.data.total
			console.log(resp.data);
		})
	}

	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
	}
	const handleCurrentChange = (val) => {
		currentPage.value = val
		query();
	}
	const handleClose = () => {
		form.value = {
			categoryId: '',
			categoryName: '',
			consultationCount: '',
			price: '',
			name: '',
			id: '',
		}
	}
	const createOrUpdate = (row) => {
		dialogFormVisible.value = true
		if (row && row.id) {
			axios.get(`chargevue/${row.id}`).then((resp) => {
				const data = Array.isArray(resp.data) ? resp.data[0] : resp.data;
				form.value = {
					id: data.id || '',
					price: data.price || '',
					categoryId: data.categoryId || (data.chargeCategory ? data.chargeCategory.id : ''),
					consultantId: data.consultantId || (data.consultant ? data.consultant.id : ''),
					consultationCount: data.consultationCount || '',
				}
			})
		} else {
			form.value = {
				categoryId: '',
				price: '',
				consultantId: '',
				consultationCount: '',
				id: '',
			}
		}
	}
	const add = () => {
		console.log("新增的id", form.value.id);
		if (form.value.id.length === 0) {
			axios.post('charge', {
				categoryId: form.value.categoryId,
				consultantId: form.value.consultantId,
				price: form.value.price
			}).then((resp) => {
				console.log('触发新增请求', resp);
				if (resp.code == 200) {
					ElMessage({
						message: '新增成功',
						type: 'success',
					})
				} else {
					ElMessage.error('新增失败')
				}
			}).finally(() => {
				query();
			});
		} else {
			axios.put(`charge`, {
				categoryId: form.value.categoryId,
				consultantId: form.value.consultantId,
				price: form.value.price,
				id: form.value.id

			}).then((resp) => {
				console.log('触发修改请求', resp);
				if (resp.code == 200) {
					ElMessage({
						message: '修改成功',
						type: 'success',
					})
				} else {
					ElMessage.error('修改失败')
				}
			}).finally(() => {
				query();
			});
		}
	}
	const remove = (row) => {
		console.log('当前行的数据', row);
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'Warning', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete(`charge/${row.id}`).then((resp) => {
					console.log('删除后：', resp);
					if (resp.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error(resp.message || '删除失败')
					}
				}).finally(() => {
					query();
				});

			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})

	}
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => {
			return item.id
		})
		console.log(multipleSelection.value);
	}
	const removeAll = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请至少选择一项');
			return;
		}

		ElMessageBox.confirm(
			'此操作将永久删除该文件, 是否继续?',
			'Warning', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			// 转换为数字数组
			const idsToDelete = multipleSelection.value.map(id => Number(id));

			// 使用data传递请求体
			axios.delete('charge', {
				data: idsToDelete,
				headers: {
					'Content-Type': 'application/json'
				}
			}).then(resp => {
				// 处理纯文本响应
				if (resp.status === 200) {
					ElMessage.success(resp.message || '删除成功');
				} else {
					ElMessage.error(resp.message || '删除失败');
				}
			}).catch(error => {
				ElMessage.error(`删除失败: ${error.response?.data || error.message}`);
			}).finally(() => {
				query();
			});
		}).catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			});
		});
	};
	onMounted(() => {
		query();
		getAllCounselorLevel();
		getAllCounselorName();
	})
</script>
<style scoped>
	.counselorPostsOne {
		width: 78px;
		background-color: #ecf5ff;
		border: 1px solid #d9ecff;
		color: #44a0ff;
		text-align: center;
		border-radius: 5px;
		padding: 5px 10px;
	}

	.counselorPostsTwo {
		width: 78px;
		background-color: #fef0f0;
		border: 1px solid #fde2e2;
		color: #f56d6d;
		text-align: center;
		border-radius: 5px;
		padding: 5px 10px;
	}

	.spanTop {
		margin: 0 10px;
		color: #696a6e;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.bt1 {
		margin-top: 10px;
		margin-left: 10px;
	}

	.div1 {
		border-bottom: 1px solid #eeeeee;
		width: 100%;
		height: 30px;
		padding-top: 15px;
		padding-left: 15px;
	}

	.div2 {
		padding-top: 15px;
	}

	.el-table {
		margin-left: 10px;
	}

	.el-pagination {
		margin-top: 10px;
		margin-left: 10px;
	}
</style>